package cn.flexui.flexuiserver.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Configuration
public class WebClientConfig {

    @Bean
    @Scope("prototype")
    @ConditionalOnMissingBean
    public WebClient.Builder webClientBuilder(ObjectProvider<WebClientCustomizer> customizerProvider) {
        WebClient.Builder builder = WebClient.builder();
        customizerProvider.orderedStream().forEach((customizer) -> customizer.customize(builder));
        return builder.filter(logRequest()).filter(logResponse());
    }

    private ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            // 打印请求详情
            System.out.println("Request: " + clientRequest.method() + " " + clientRequest.url());
            return Mono.just(clientRequest);
        });
    }

    private ExchangeFilterFunction logResponse() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            // 缓存响应体
            return clientResponse.bodyToMono(String.class)
                    .flatMap(responseBody -> {
                        String modifiedResponseBody = modifyResponse(responseBody);
                        return Mono.just(clientResponse)
                                .flatMap(originalResponse -> {
                                    // 创建一个新的 ClientResponse 对象
                                    return Mono.just(ClientResponse.from(originalResponse)
                                            .body(modifiedResponseBody)
                                            .build());
                                });
                    });
        });
    }

    // 示例修改函数
    private String modifyResponse(String responseBody) {
        return responseBody.replace("\"finish_reason\":\"\"", "\"finish_reason\":null");
    }
}
